package com.z.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.z.common.base.Results;
import com.z.admin.dao.RoleMapper;
import com.z.admin.dao.UserRoleMapper;
import com.z.admin.entity.Role;
import com.z.admin.service.IRoleService;
import com.z.admin.vo.RoleDto;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author z
 * @since 2022-02-13
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public List<Role> findAll() {
        return roleMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public Results<Role> findByPage(Integer offset, Integer limit) {
        return Results.success(roleMapper.conutAllRoles(), roleMapper.findRoleByPage(offset, limit));
    }
    @Override
    public Role findById(String id) {
        return roleMapper.selectById(Long.parseLong(id));
    }

    @Override
    public void deleteById(String id) {
        userRoleMapper.deleteByRoleId(id);
        roleMapper.deleteById(Long.parseLong(id));
    }

    @Override
    public void update(RoleDto user, Integer roleId) {
       // roleMapper.updateById(user);
    }

    @Override
    public Results<Role> findPageByMap(Map<String, Object> map, Integer offset, Integer limit) {
        StringBuffer where = new StringBuffer("");
        if(map != null && map.size() > 0){
            where.append("where ");
            for(Map.Entry<String, Object> entry : map.entrySet()){
                String[] strArr = entry.getKey().split("_");
                where.append(strArr[0]+" ");
                if(strArr[1].equals("like")){
                    where.append("like '%" +entry.getValue()+"%' and ");
                }else{
                    where.append("= '" +entry.getValue()+"' and ");
                }
            }
            where.delete(where.length()-4, where.length());
        }
        return Results.success(roleMapper.conutByMap(where.toString()), roleMapper.findPageByWhereSql(where.toString(), offset, limit));
    }

    @Override
    public Role findRoleByName(String name) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        return roleMapper.selectOne(wrapper);
    }
}
